<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      :finished-text="finishedText"
      @load="onLoad"
    >
      <van-cell
        v-for="(res, i) in results"
        :key="i"
        :title="res.title"
        :to="{
          name: 'article',
          params: { artID: res.art_id }
        }"
      ></van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSearch } from '@/api/search.js'
export default {
  name: 'SearchResult',
  data() {
    return {
      page: 1,
      pageCount: 20,
      results: [],
      loading: false,
      finished: false,
      finishedText: '已加载完毕'
    }
  },
  props: {
    searchContent: {
      type: String,
      required: true
    }
  },
  methods: {
    // 定义获取搜索结果函数
    async getSearchResult(searchKeyWord) {
      try {
        const { data: res } = await getSearch(
          this.page,
          this.pageCount,
          searchKeyWord
        )
        this.results.push(...res.data.results)
        // 未搜索到情况
        if (this.results.length === 0) {
          this.finishedText = '未搜索到相关内容'
          this.loading = false
          this.finished = true
          return
        }
        // 搜索到情况
        if (res.data.results.length < this.pageCount) {
          this.loading = false
          this.finished = true
          return
        }
        this.loading = false
        this.page += 1
      } catch (error) {
        this.$toast.fail('服务器繁忙，请稍后再试哟')
      }
    },
    onLoad() {
      this.getSearchResult(this.searchContent)
    }
  }
  /*   ,
  watch: {
    searchContent: {
      immediate: true,
      handler: function (newVal) {
        this.getSearchResult(newVal)
      }
    }
  } */
}
</script>

<style lang="less" scoped>
</style>
